package com.qiaoya.nettyConnProxy;

import java.text.SimpleDateFormat;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class NettyServerHandler extends ChannelInboundHandlerAdapter{
	//每个信息入站都会调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception {
//        ByteBuf buf = (ByteBuf) message;
//        System.out.println("The server receive msg :" + buf.toString());
//        ctx.write(buf); 
//    	ByteBuf buf=(ByteBuf) message;
//        byte[] req=new byte[buf.readableBytes()];
//        buf.readBytes(req);   
//        String strMsg = new String(req);
        
        String strMsg = (String) message;
		SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String TimeString = time.format(new java.util.Date());
		System.out.println("msgserver recv data from remove server---"+ TimeString+":" + strMsg);
		if(strMsg.contains("{") && strMsg.contains("}") && strMsg.contains(":")){
			AKXWatchProtocolDecoder.processPacketHandler(strMsg.trim().substring(1, strMsg.length() - 1), ctx);
		}
    }

    //通知处理器最后的channelread()是当前批处理中的最后一条消息时调用
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    //读操作时捕获到异常时调用
    @Override
    public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}
